<?php
	//error_reporting(0);
	include_once './facebook.php';
	include_once './config.php';
	include_once './lib.php';

	$facebook = new Facebook($api_key, $secret);
	
	$auth_token = "";
	if($_GET['auth_token'] != ""){
		$auth_token = $_GET['auth_token'];
		$results = $facebook->api_client->auth_getSession($auth_token);


		$query = "SELECT name, hometown_location, pic_square, current_location, affiliations, uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=".$results['uid'].") ORDER BY name";
		$array = $facebook->api_client->fql_query($query);

		//print_r($array);

		$fileString = '<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">
<document>
';

		$cities = array();
		$zips = array();

		$coords = "341224";

		for($i=0; $i < count($array); $i++){
			//only use friend if they have location information
			if($array[$i]['hometown_location']['city'] != ""){

				//key for google maps API
				$key = "ABQIAAAAYgIFcdB73ikjsshF47qFhRT9MMXG_tYPVLibiAtjK-zmIeBb9RTQy57sFP4wbxEGLiuFm3mV7BVEKQ";

				//city query optimisation
				if($array[$i]['hometown_location']['zip'] != ""){

					//print "<br>zip: ".$array[$i]['hometown_location']['zip'];

					if(array_key_exists($array[$i]['hometown_location']['zip'], $zips)){
						$coords = $zips[$array[$i]['hometown_location']['zip']];
						//print " -exists ".$coords;
					}else{
					//print " -nonexistent ";
						usleep(5000);
						// Desired address
						$address = "http://maps.google.com/maps/geo?q=".$array[$i]['hometown_location']['zip']."&output=xml&key=$key";

						// Retrieve the URL contents as XML from Google
						$xmlString = file_get_contents($address);

						//scan XML string for contents of the coord tags
						if(preg_match("/<coordinates>(.*)<\/coordinates>/i",$xmlString, $tag_contents)){
							$coords = $tag_contents[1];
							$zips[$array[$i]['hometown_location']['zip']] = $coords;
						}else{
							continue;
						}
					}

				}else{

					$city = preg_replace('/\s/', '+', $array[$i]['hometown_location']['city']);
					//print "<br>city: ".$city;

					if(array_key_exists($array[$i]['hometown_location']['city'], $cities)){
						$coords = $cities[$array[$i]['hometown_location']['city']];
						//print " -exists".$coords;
					}else{
					//print " -nonexistent ";
						usleep(5000);
						$city = preg_replace('/\s/', '+', $array[$i]['hometown_location']['city']);
						$state = preg_replace('/\s/', '+', $array[$i]['hometown_location']['state']);
						// Desired address
						$address = "http://maps.google.com/maps/geo?q=".$city.",+".$state."&output=xml&key=$key";

						// Retrieve the URL contents as XML from Google
						$xmlString = file_get_contents($address);

						//scan XML string for contents of the coord tags
						if(preg_match("/<coordinates>(.*)<\/coordinates>/i",$xmlString, $tag_contents)){
							$coords = $tag_contents[1];
							$cities[$array[$i]['hometown_location']['city']] = $coords;
						}else{
							continue;
						}
					}
				}//end query optimisation

				$fileString = $fileString."
	<Placemark>
		<name>".$array[$i]['name']."</name>
		<description><![CDATA[
";
				if($array[$i]['pic_square'] != ""){
					$fileString = $fileString."
			<a href='http://facebook.com/profile.php?id=".$array[$i]['uid']."&ref=nf' target='_blank'><img src='".$array[$i]['pic_square']."' style='border: 0px; margin: 10px; float: left;' /></a>
";
				}

				$fileString = $fileString."
			<span style='font-size: 14px; color: gray; '>Hometown: ".$array[$i]['hometown_location']['city']."</span><br>
";
				if($array[$i]['current_location']['city'] != ""){
					$fileString = $fileString."
			<span style='font-size: 14px; color: gray; '>Current Location: ".$array[$i]['current_location']['city']."</span><br>
";
				}
				if($array[$i]['affiliations']['name'] != ""){
					$fileString = $fileString."
			<span style='font-size: 14px; color: gray; '>Network: ".$array[$i]['affiliations']['name']."</span><br>
";
				}

				$fileString = $fileString."
		<br style='clear: both;'><br style='clear: both;'>]]></description>
		<Point>
			<coordinates><![CDATA[".$coords."]]></coordinates>
		</Point>
	</Placemark>
";
			}
		}

		$fileString = $fileString."
</document>
</kml>
";

		$fileName = "./kmlFiles/".$results['uid'].".kml";

		if(file_exists($fileName)){
			unlink($fileName);
		}

		//open file
		$fp = fopen($fileName, 'w') or die("Error!! Could not open file $fileName");

		//write to file
		if(fwrite($fp, $fileString) === FALSE){
			echo "Cannot write to file ($fileName)";
			exit;
		}

		//close the file
		fclose($fp);

?>

<html>
	<head>
		<script type="text/javascript">
		<!--
		function redirectMe(){
		    window.location = "./faceMap.php?uid=<?php print $results['uid']; ?>";
		}
		//-->
		</script>
	</head>
	<body onload="redirectMe();">

	</body>


<?php

	}else{
		//$user_id = $facebook->require_login();
		print "<a href='http://www.facebook.com/login.php?api_key=".$api_key."&v=1.0'><img src='http://teamname.gan.tjohns.net/ui_release1/img/facebook_login.gif'></a>";
	}

?>